package com.neusoft.resturant.common.interceptor;

import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.exception.BizException;
import com.neusoft.resturant.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: resturant
 * @description:
 * @author: lydms
 * @create: 2023-11-29 14:30
 **/




    @Component
    public class AuthInterceptor implements HandlerInterceptor {

        @Resource
        private RedisTemplate redisTemplate;

        // 前置拦截
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("拦截器进行拦截");
            String token = request.getHeader("token");
            System.out.println("token:" + token);
            if (token == null) {
                throw new BizException(401, "认证失败，非法用户");
            }
            String userJson = (String) redisTemplate.opsForValue().get(token);
            System.out.println(userJson);
            if (userJson == null) {
                throw new BizException(401, "认证失败，非法用户");
            }
            System.out.println("通过");
            SysUser curUser = JSON.parseObject(userJson,SysUser.class);
            request.setAttribute("userId", curUser.getUserId());
            return true;
        }
    }


